from django.shortcuts import render

import json
import datetime
from lib.http import render_json
from user.models import User,Permission,Roles,RolePermRelation
from goods.models import Goods,GoodsUserRelation


def goods(request):
  """获取当前宠物信息"""
  if request.method == 'POST':
    json_str = request.body
    if not json_str:
        result = {'code': 202, 'error': 'Please POST data!!!'}
        return render_json(result)
    json_obj = json.loads(json_str)
    print(json_obj)
    phonenum = json_obj.get('username')
    keys = json_obj.get('keys')
    is_phonenum=User.objects.filter(phonenum=phonenum,key=keys).only('id','phonenum').first()
    if is_phonenum:
      goods = Goods.objects.all()
      res_list=[]
      now = datetime.datetime.now()
      now_hour = now.hour
      now_minute = now.minute
      print('now_time', now_hour, now_minute)
      try:
          for good in goods:
            print('2222',good.id)
            res1=GoodsUserRelation.objects.filter(goods_id=good.id, user_id=is_phonenum.id).last()
            print(res1,type(res1))

            start_time = (good.start_time).split(":")
            end_time = (good.end_time).split(":")
            start_hour = int(start_time[0])
            start_minute = int(start_time[1])
            print('start_time', start_hour, start_minute)
            end_hour = int(end_time[0])
            end_minute = int(end_time[1])
            print('end_time', end_hour, end_minute)
            if now_hour<start_hour:
                if res1.state==2:
                    state=2
                else:state=1
            elif now_hour==start_hour:
                if now_minute<=start_minute:
                    state = 1
                elif start_minute<now_minute<=end_minute:
                    state=3
                else:state=0
            else:
                state=0

            try:
                result_pet = {'id':good.id,
                          'pic_path':good.pic_path,
                          'name':good.name,
                          'price':good.price,
                          # "order":good.order,
                          "profit_per":"%d%%"%((good.profit_per) * 100),
                          "profit_time":good.profit_time,
                          "goods_num":good.goods_num,
                          "pet_price":good.pet_price,
                          'start_time':good.start_time,
                          'end_time':good.end_time,
                          'user_id': is_phonenum.id,
                          'state':state,
                          }
                res_list.append(result_pet)
            except Exception as e:
                print(e)
      except Exception as e:
          print(e)
    # res = [good.to_dict() for good in goods]
      result = {"data": res_list}
      return render_json(result)
    else:
        data='非法入侵'
        return render_json(data,code=203)

def yuyue(request):
    """点击预约 修改宠物信息"""
    json_str = request.body
    if not json_str:
        result = {'code': 202, 'error': 'Please POST data!!!'}
        return render_json(result)
    json_obj = json.loads(json_str)
    print(json_obj)
    phonenum = json_obj.get('phone')
    keys = json_obj.get('keys')
    state = json_obj.get('state')
    pet_id = json_obj.get('pet_id')
    pet_pri = Goods.objects.filter(id=pet_id).only('pet_price').first()
    is_user = User.objects.filter(phonenum=phonenum,
        key=keys).only('id', 'has_wx','has_ali','has_yhk','has_renzheng','user_price').first()
    print('11111111',is_user.user_price,pet_pri.pet_price)
    if is_user:
        if (is_user.has_renzheng)==False:
            data="don't has identify"
            return render_json(data,code=100)
        if (is_user.has_wx or is_user.has_yhk or is_user.has_ali)==False:
            data="don't add skm"
            return render_json(data,code=101)
        user_price=is_user.user_price-pet_pri.pet_price
        if user_price>=0:
            try:
                GoodsUserRelation.objects.create(goods_id=pet_id,user_id=is_user.id,state=state)
                is_user.user_price=user_price
                print('111111112',is_user.user_price)
                is_user.save()
                result = {'code': 200, 'res': '预约成功!!!'}
                return render_json(result)
            except:
                result = {'code': 102, 'res': '未知错误，预约失败!!!'}
                return render_json(data=result, code=102)
        else:return render_json(data='余额不足', code=103)
    else:
        data = '非法入侵'
        return render_json(data=data, code=203)

def get_yuyue(request):
    """获取预约结果"""
    json_str = request.body
    if not json_str:
        result = {'code': 202, 'error': 'Please POST data!!!'}
        return render_json(result)
    json_obj = json.loads(json_str)
    print(json_obj)
    phonenum = json_obj.get('phone')
    keys = json_obj.get('keys')
    # state = json_obj.get('state')
    # pet_id = json_obj.get('pet_id')
    is_user = User.objects.filter(phonenum=phonenum,
                                  key=keys).only('id').first()
    if is_user:
        try:
            res_list=GoodsUserRelation.objects.filter(user_id=is_user.id,state=2)
            pet_list=[]
            for good in res_list:
                pet=Goods.objects.filter(id=good.goods_id).only('name').first()
                res_dic={
                    'name':pet.name,
                    # 'profit':pet.profit,
                    # 'name':pet.name,
                    'pet_id': good.goods_id,
                    'user_id': good.user_id,
                    'state': good.state,
                    "has_pet": good.has_pet,
                    "price": good.price,
                    "profit_per": "%d%%"%((pet.profit_per) * 100),
                    "profit_time": pet.profit_time,
                    'get_time': good.get_time.strftime("%Y-%m-%d %H:%M:%S"),

                }
                pet_list.append(res_dic)
            try:
                res5_list = GoodsUserRelation.objects.filter(user_id=is_user.id, state=5)
                pet5_list = []
                for good in res5_list:
                    pet = Goods.objects.filter(id=good.goods_id).only('name').first()
                    res_dic = {
                        'name': pet.name,
                        'pet_price':pet.pet_price,
                        'id':good.id,
                        'pet_id': good.goods_id,
                        'user_id': good.user_id,
                        'state': good.state,
                        "has_pet": good.has_pet,
                        "price": good.price,
                        "profit_per": "%d%%"%((pet.profit_per) * 100),
                        "profit_time": pet.profit_time,
                        'get_time': good.get_time.strftime("%Y-%m-%d %H:%M:%S"),
                        # 'get_time1': (good.get_time + datetime.timedelta(days=3)).strftime("%Y-%m-%d %H:%M:%S"),
                    }
                    pet5_list.append(res_dic)
            except:
                result = {'code': 103, 'res': '未知错误，获取数据失败!!!'}
                return render_json(data=result, code=103)
            result={'yuyue':pet_list,'yuyue_failed':pet5_list[::-1]}    #[::-1]将列表反转，实现前端倒叙显示
            return render_json(result)
        except:
            result = {'code': 102, 'res': '未知错误，获取数据失败!!!'}
            return render_json(data=result, code=102)
    else:
        data = '非法入侵'
        return render_json(data, code=203)

def yuyue_failed(request):
    """预约匹配失败"""
    json_str = request.body
    if not json_str:
        result = {'code': 202, 'error': 'Please POST data!!!'}
        return render_json(result)
    json_obj = json.loads(json_str)
    print(json_obj)
    pet_id = json_obj.get('pet_id')
    user_id = json_obj.get('user_id')
    state = json_obj.get('state')
    try:
        GoodsUserRelation.objects.filter(user_id=user_id,goods_id=pet_id).update(state=state)
        #filter之后的update不会出发auto_now的时间更新，save或者create方法会触发，
        # 如果update需要出发时间更新，需要手动更新时间，比如：get_time=datetime.now()
        return render_json(data='success')
    except:
        result = {'code': 102, 'res': '未知错误，获取数据失败!!!'}
        return render_json(data=result, code=102)


def select_has_pets(request):
    """查询所有拥有宠物的人 后台使用"""
    pet_lists = GoodsUserRelation.objects.filter(has_pet=1)
    pet1_list = []
    pet2_list = []
    pet3_list = []
    pet4_list = []
    pet5_list = []
    pet6_list = []
    for pet in pet_lists:
        if pet.goods_id == 1:
            res = pet.to_dict()
            pet1_list.append(res)
        elif pet.goods_id == 2:
            res = pet.to_dict()
            pet2_list.append(res)
        elif pet.goods_id == 3:
            res = pet.to_dict()
            pet3_list.append(res)
        elif pet.goods_id == 4:
            res = pet.to_dict()
            pet4_list.append(res)
        elif pet.goods_id == 5:
            res = pet.to_dict()
            pet5_list.append(res)
        elif pet.goods_id == 6:
            res = pet.to_dict()
            pet6_list.append(res)
    result = {
        'pet1_list': pet1_list,
        'pet2_list': pet2_list,
        'pet3_list': pet3_list,
        'pet4_list': pet4_list,
        'pet5_list': pet5_list,
        'pet6_list': pet6_list,
    }
    return render_json(data=result, code=200)

def select_pet(request):
    """查询当前用户所拥有的宠物"""
    json_str = request.body
    if not json_str:
        result = {'code': 202, 'error': 'Please POST data!!!'}
        return render_json(result)
    json_obj = json.loads(json_str)
    print(json_obj)
    key = json_obj.get('keys')
    phone = json_obj.get('phone')
    user=User.objects.filter(phonenum=phone,key=key).only('id').first()
    if user:
        pet_lists=GoodsUserRelation.objects.filter(user_id=user.id,has_pet=1)
        if pet_lists:
            pet1_list=[]
            for pet in pet_lists:
                res = pet.to_dict()
                good = Goods.objects.filter(id=pet.id).only('profit_per','profit_time').first()
                res['perfit']=pet.price * good.profit_per
                pet1_list.append(res)
            return render_json(data=pet1_list, code=200)
        else:
            result = {'code': 100, 'res': '当前用户没有宠物!!!'}
            return render_json(data=result, code=100)
    else:
        result = {'code': 101, 'res': '用户错误!!!'}
        return render_json(data=result, code=101)

def select_yuyue(request):
    """查询有多少人在预约中"""
    pet_lists=GoodsUserRelation.objects.filter(state=2)
    pet1_list = []
    pet2_list = []
    pet3_list = []
    pet4_list = []
    pet5_list = []
    pet6_list = []
    for pet in pet_lists:
        if pet.goods_id==1:
            res = pet.to_dict()
            pet1_list.append(res)
        elif pet.goods_id==2:
            res = pet.to_dict()
            pet2_list.append(res)
        elif pet.goods_id==3:
            res = pet.to_dict()
            pet3_list.append(res)
        elif pet.goods_id==4:
            res = pet.to_dict()
            pet4_list.append(res)
        elif pet.goods_id==5:
            res = pet.to_dict()
            pet5_list.append(res)
        elif pet.goods_id==6:
            res = pet.to_dict()
            pet6_list.append(res)
    result = {
        'pet1_list': pet1_list,
        'pet2_list': pet2_list,
        'pet3_list': pet3_list,
        'pet4_list': pet4_list,
        'pet5_list': pet5_list,
        'pet6_list': pet6_list,
    }
    return render_json(data=result, code=200)


def sell_pet(request):
    """出售宠物"""
    json_str = request.body
    if not json_str:
        result = {'code': 202, 'error': 'Please POST data!!!'}
        return render_json(result)
    json_obj = json.loads(json_str)
    print(json_obj)
    key = json_obj.get('key')
    phone = json_obj.get('phone')
    pet_id = json_obj.get('pet_id')
    price = json_obj.get('price')
    id = json_obj.get('id')
    #计算收益周期是否达到
    profits = Goods.objects.filter(id=pet_id).only('profit_time').first()
    good = GoodsUserRelation.objects.filter(goods_id=pet_id).only('get_time').first()
    profit_time=(good.get_time + datetime.timedelta(days=profits.profit_time))
    now_time=datetime.datetime.now()
    if now_time>profit_time or good.state==8:
        user = User.objects.filter(phonenum=phone, key=key).only('id').first()
        if user:
            try:
                GoodsUserRelation.objects.filter(id=id,user_id=user.id, goods_id=pet_id).update(state=7,price=price)
                result = {'code': 200, 'res': '出售宠物成功!!!'}
                return render_json(data=result, code=200)
            except:
                result = {'code': 102, 'res': '出售宠物，更新数据库失败!!!'}
                return render_json(data=result, code=102)
        else:
            result = {'code': 101, 'res': '用户错误!!!'}
            return render_json(data=result, code=101)
    else:
        result = {'code': 103, 'res': '该宠物还在收益期中，不能出售!!!'}
        return render_json(data=result, code=103)

def distribute_pet(request):
    """手动为用户分配宠物"""
    json_str = request.body
    if not json_str:
        result = {'code': 202, 'error': 'Please POST data!!!'}
        return render_json(result)
    json_obj = json.loads(json_str)
    print(json_obj)
    goods_id = json_obj.get('goods_id')
    phone = json_obj.get('phone')
    price = json_obj.get('price')
    user = User.objects.filter(phonenum=phone).only('id').first()
    if user:
        try:
            GoodsUserRelation.objects.create(goods_id=goods_id, user_id=user.id, state=8, has_pet=1, price=price)
            result = {'code': 200, 'res': '分配成功!!!'}
            return render_json(result)
        except:
            result = {'code': 100, 'res': '未知错误，预约失败!!!'}
            return render_json(data=result, code=100)
    else:
        result = {'code': 101, 'res': '用户错误!!!'}
        return render_json(data=result, code=101)

def pipei_auto(request):
    """开启自动匹配"""
    pass

def pipei_hand(request):
    """手动为某个用户匹配"""
    pass

